<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

class OwnserviceControllerTransaction extends JController
{
	/**
	 * Controller construct
	*/
	function __construct(){
		parent::__construct();
	}

	/**
	 * Method to get transaction details
	 *
	 * @return void
	 * @since 1.0
	*/
	function detail() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canView	= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('default');

		// Display the view
		$view->display();
	}

	/**
	 * Method to get form  edit transaction
	 *
	 * @return void
	 * @since 1.0
	 */
	function edit(){

		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canEdit	= Ownservice::checkAccess('transaction', 'edit', 'transaction', 'all');
			if (!$canEdit) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('form');

		// Display the view
		$view->display();

	}

	/**
	* Method to add an custom account
	*
	* @access	public
	* @since	1.0
	*/
	function add() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canAdd		= Ownservice::checkAccess('transaction', 'add', 'transaction', 'all');
			if (!$canAdd) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('form');

		// Display the view
		$view->display();
	}

	/**
	* Method to print transaction details
	*
	* @access	public
	* @since	1.0
	*/
	function printDetails() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canView		= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('print');

		// Display the view
		$view->display();
	}

	/**
	* Method to print transaction invoice
	*
	* @access	public
	* @since	1.0
	*/
	function printReceipt() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canView		= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('receipt');

		// Display the view
		$view->display();
	}

	/**
	 * Logic to save transaction
	 * 
	 * @access public
	 * @return void
	*/
	function save(){

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		$user	= & JFactory::getUser();
		$app	= &	JFactory::getApplication();
		$db		= & JFactory::getDBO();

		// Get vars
		$post = JRequest::get( 'post' );

		$model = $this->getModel('Transaction');

		if($model->canTransfer($post['user_id'])) {
			if($model->store($post)) {
				$msg = JText::_('OWNSERVICE_TRANSFER_SAVED');
			}else {
				$type = 'error';
				$msg = JText::_('OWNSERVICE_ERROR_SAVING_TRANSFER');
			}

			$link = JRoute::_('index.php?option=com_ownservice&amp;view=transaction&amp;id='.$model->get('id'));
		} else {
			$type	= 'error';
			$msg	= JText::_('OWNSERVICE_EXPIRE');

			$link = JRoute::_('index.php?option=com_ownservice&amp;controller=transaction&amp;task=add');
		}

		$this->setRedirect($link, $msg, $type);
	}

	/**
	 * Method to get form  approval request
	 *
	 * @return void
	 * @since 1.0
	 */
	function paidtransactions(){

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canRequestApproval= Ownservice::checkAccess('transaction', 'approval', 'transaction', 'all');

			if ( !$canRequestApproval ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('paidtransactions');

		// Display the view
		$view->display();
	}

	/**
	 * Method to get request approval
	 *
	 * @return void
	 * @since 1.0
	 */
	function requestapproval() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransfer= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if ( !$canTransfer ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('requestapproval');

		// Display the view
		$view->display();
	}
	
	/**
	 * Method to get request approval corrected
	 *
	 * @return void
	 * @since 1.0
	 */
	function requestapprovalcorrected()
	{
		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransfer= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if ( !$canTransfer ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('requestapprovalcorrected');

		// Display the view
		$view->display();
	}

	/**
	 * Method get failed transactions
	 *
	 * @return void
	 * @since 1.0
	*/
	function failedtransactions()
	{
		global $mainframe;

		// Initialise variables
		$user			= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid			= $user->gid;

		if($gid < 25) {
			$canF= Ownservice::checkAccess('transaction', 'failed', 'transaction', 'all');
			if ( !$canF ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('failedtransactions');

		// Display the view
		$view->display();
	}

	/**
	 * Method get cancelled transactions
	 *
	 * @return void
	 * @since 1.0
	*/
	function cancelledtransactions()
	{
		global $mainframe;

		// Initialise variables
		$user			= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid			= $user->gid;

		if($gid < 25) {
			$canC= Ownservice::checkAccess('transaction', 'cancelled', 'transaction', 'all');
			if ( !$canC ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('cancelledtransactions');

		// Display the view
		$view->display();
	}
	
	/**
	 * Method get corrected transactions
	 *
	 * @return void
	 * @since 1.0
	*/
	function correctedtransactions()
	{
		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canC= Ownservice::checkAccess('transaction', 'corrected', 'transaction', 'all');
			if ( !$canC ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('correctedtransactions');

		// Display the view
		$view->display();
	}

	/**
	 * Method get account receive
	 *
	 * @return string
	 * @since 1.5
	*/
	function getAccounts(){

		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		$model = & $this->getModel('Transaction');

		//Get var
		$id = JRequest::getVar('id', 0, 'post', 'int');

		//Get data form the model
		$banks = $model->getAccounts($id);
		
		//build transfer to select list
		echo OwnserviceHelper::buildbanksselect($banks, 'account','',true, 'class="inputbox" style="width:250px;"');
		
		exit();
	}

	/**
	 * Method to get currency list
	 *
	 * @return string
	 * @since 1.5
	*/
	function getCurrency() {
			
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		$user 		=& JFactory::getUser();
		
		$id			= JRequest::getVar('id', 0, 'post', 'int');
		
		//get Data from the model
		$model 		= $this->getModel('Transaction');
		$profile 	= $model->getUser($id);
		$currencies = $model->getCurrencies($profile->branch_id);
		
		//build currency select list
		echo $currency	= OwnserviceHelper::buildcurrenciesselect($currencies, 'rate_id',$profile->rate_id,true, 'class="inputbox required" style="width:250px;"');

		exit();
	}
	
	/**
	 * Method to get exchange money rate
	 *
	 * @return string
	 * @since 1.5
	*/
	function getExchange() {
			
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		//Initialise
		$user 		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDbo();
		
		//get vars
		$id			= & JRequest::getVar('id', 0 , 'post', 'int');
		$rate_id 	= & JRequest::getVar('rate_id', 0, 'post', 'int');
		
		$query = ' SELECT p.branch_id '
				.' FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.$id;
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();
		
		/*$query = 'SELECT r.* FROM #__ownservice_exchangerates AS r '
			.' LEFT JOIN #__ownservice_rate_branch_relations AS rel ON rel.rate_id=r.id '
			.' WHERE r.code='.$db->Quote($ratecode).' AND rel.branch_id='.$branch_id
			;*/
		$query = ' SELECT r. *, c.code '
				.' FROM #__ownservice_exchangerates AS r '
				.' LEFT JOIN #__ownservice_currencies AS c ON c.id=r.currency_id '
				.' WHERE r.id='.$rate_id
				.' AND r.branch_id='.$branch_id
				;
		
		$db->setQuery($query);
		$row = $db->loadObject();
		
		if(!is_object($row)){
			$row = new stdClass();
			$row->rate = null;
			$row->code = null;
		}
		
		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		
		echo json_encode($row);
		
		exit();
	}

	/**
	 * Method get total exchange money
	 *
	 * @return string
	 * @since 1.0
	*/
	function getTotal() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		$db = & JFactory::getDBO();

		$post = JRequest::get( 'post' );
		
		//get branch ID
		$query = ' SELECT p.branch_id FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.$post['user_id'];
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();
		
		//get rate ID
		/*$query = 'SELECT r.id FROM #__ownservice_exchangerates AS r '
				.' LEFT JOIN #__ownservice_rate_branch_relations AS rel ON rel.rate_id=r.id '
				.' WHERE r.code='.$db->Quote($post['rate_code']).' AND rel.branch_id='.$branch_id
			;*/
		$query = ' SELECT r.id  '
				.' FROM #__ownservice_exchangerates AS r '
				.' WHERE r.id='.$post['rate_id']
				.' AND r.branch_id='.$branch_id;
		
		$db->setQuery($query);
		$rate_id = $db->loadResult();
		
		//get fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'fee' AND `from` <=".$post['amount']." AND `to` >=".$post['amount'];
		$db->setQuery($query);
		$fee = $db->loadResult();

		$fee = $fee?$fee:'0.00';
		
		//get destination fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'destinationfee' AND `from` <=".$post['amount']." AND `to` >=".$post['amount'];
		$db->setQuery($query);
		$bankfee = $db->loadResult();
		
		$bankfee = $bankfee?$bankfee:'0.00';

		$total = round( ( ($post['amount'] * ($post['rate'] + $post['extrarate']) ) - ($bankfee + $post['extrabfee']) ), 2);
		
		list($a1, $a2)	= explode('.', $total);
		$temp 			= substr($a2, -1);
		
		if($temp > 0 && $temp < 5){
			$num = 5 - $temp;
		} elseif($temp > 5){
			$num = 10 - $temp; 
		}else{
			$num = 0;
		}
		
		$total = $total+('0.0'.$num);

		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo "{'total': '".$total."', 'fee': '".$fee."', 'bankfee':'".$bankfee."'}";
		exit();
	}

	/**
	 * Method get amount transfer money
	 *
	 * @return string
	 * @since 1.0
	 */
	function getTransfer() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		$db = & JFactory::getDBO();

		$post = JRequest::get( 'post' );

		//get branch ID
		$query = ' SELECT p.branch_id FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.$post['user_id'];
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();
		
		//get rate ID
		/*$query = 'SELECT r.id FROM #__ownservice_exchangerates AS r '
				.' LEFT JOIN #__ownservice_rate_branch_relations AS rel ON rel.rate_id=r.id '
				.' WHERE r.code='.$db->Quote($post['rate_code']).' AND rel.branch_id='.$branch_id
			;*/
			
		$query = ' SELECT r.id '
				.' FROM #__ownservice_exchangerates AS r '
				.' WHERE r.id='.$post['rate_id']
				.' AND r.branch_id='.$branch_id
				;
				
		$db->setQuery($query);
		$rate_id 		= $db->loadResult();
		
		$amount 		= round(($post['sumtotal'] / ($post['rate'] + $post['extrarate'])), 2);
		
		list($a1, $a2)	= explode('.', $amount);
		$temp 			= substr($a2, -1);
		
		if($temp > 0 && $temp < 5){
			$num = 5 - $temp;
		} elseif($temp > 5){
			$num = 10 - $temp; 
		}else{
			$num = 0;
		}
		
		$amount = $amount+('0.0'.$num);
		
		//get fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'fee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$fee = $db->loadResult();

		$fee = $fee?$fee:'0.00';
		
		//get destination fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'destinationfee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$bankfee = $db->loadResult();
		
		$bankfee = $bankfee?$bankfee:'0.00';

		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo "{'amount': '".$amount."', 'fee': '".$fee."', 'bankfee':'".$bankfee."'}";
		exit();
	}
	
	/**
	 * Method to get other detail
	 *
	 * @return string 
	 * @since 1.0
	*/
	function getotherdetail()
	{
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		$id			= JRequest::getVar('id', 0, 'post', 'int');
		$account  = JRequest::getVar('account', '', 'post', 'string');
		
		//get Data from the model
		$model 	= $this->getModel('Transaction');
		$profile 	= $model->getUser($id);
		$account	= $model->getAccount($account);
		
		if($account->birthday == '0000-00-00') {
			$birthday = null;
		} else {
			$birthday = $account->birthday;
		}
		
		$html ='<table width="100%" cellpadding="1" cellspacing="1">';
		$html .='<tr>';
			$html .='<td class="key">'.JText::_('OWNSERVICE_OCCUPATION').'</td>';
			$html .= '<td><input type="text"  name="occupation" id="occupation" value="'.$profile->occupation.'" /></td>';
		$html .= '</tr>';
		$html .='<tr>';
			$html .='<td class="key">'.JText::_('OWNSERVICE_BIRTHDAY_RECEIVER').'</td>';
			$html .= '<td>'.JHTML::_('calendar', $birthday, 'birthday', 'birthday', '%Y-%m-%d',array('class'=>'inputbox')).'</td>';
		$html .= '</tr>';
		$html .='</table>';
		
		echo $html;
		
		exit();
	}

	/**
	 * Logic to delete transaction
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	*/
	function delete() {

		global $mainframe;

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		//Initialise variables
		$user		 = & JFactory::getUser();

		$id			= JRequest::getVar( 'id', 0, 'post', 'int' );
		$model 		= $this->getModel('Transactions');

		if($user->gid < 25) {
			$canDelete		= Ownservice::checkAccess('transaction', 'delete', 'transaction', 'all');

			if ( !$canDelete ) {
				
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		if ($id < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_ITEM_DELETED' ) );

		} else {

			if (!$model->delete($id)) {
				JError::raiseError(500, JText::_( 'OWNSERVICE_TRANSACTION_FAILED' ));
			}
			
			$msg = JText::_( 'OWNSERVICE_TRANSACTION_DELETED' );
		}
		
		$this->setRedirect( 'index.php?option=com_ownservice&view=transactions', $msg );
	}

	/**
	 * logic for cancel an action
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	 */
	function cancel()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		$app =& JFactory::getApplication();
		
		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect( $link );
	}

	/**
	 * Logic to submit transaction to request approval
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */
	function approval() {

		global $mainframe, $option;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();

		//set vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canRequestApproval	= Ownservice::checkAccess('transaction', 'approval', 'transaction', 'all');
			if (!$canRequestApproval) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get Vars
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVEL' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateRequestApproval($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_REQUEST_APPROVAL' );			
		}

		$mainframe->enqueueMessage($msg);

		return $this->execute('paidtransactions');
	}

	/**
	 * Logic to submit transaction to request approval corrected
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */   
	function approvalcorrected()
	{
		global $mainframe, $option;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();

		//set vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canRequestApproval	= Ownservice::checkAccess('transaction', 'corrected', 'transaction', 'all');
			if (!$canRequestApproval) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get Vars
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVEL' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateRequestApprovalCorrected($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_REQUEST_APPROVAL_CORRECTED' );			
		}

		$mainframe->enqueueMessage($msg);

		return $this->execute('correctedtransactions');
	}

	/**
	 * Logic to resubmit transaction
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */
	function resubmit()
	{
		global $mainframe;
		
		//Initialise variables
		$user		= &JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();
		
		//get vars
		$gid		= $user->gid;
		
		if($gid < 25) {
			$canF= Ownservice::checkAccess('transaction', 'failed', 'transaction', 'all');
			if ( !$canF ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get Vars
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_FAILED_TRANSACTIONS' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateCorrected($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_TRANSACTION_CORRECTED' );			
		}

		$mainframe->enqueueMessage($msg);	
		
		return $this->execute('failedtransactions');
	}

	/**
	 * Method to approve to transferrer
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */
	function approve() {

		global $mainframe, $option;

		//Initialise variables
		$user		= &JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canApprove	= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if (!$canApprove){
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}
		
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVAL_CORRECTED' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateApprove($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' . JText::_( 'OWNSERVICE_APPROVE' );
		}
		
		$mainframe->enqueueMessage($msg);

		return $this->execute('requestapprovalcorrected');
	}

	/**
	 * Logic to submit transaction to receiving transfer
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/

	function transfer() {
		
		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');
		
		global $mainframe, $option;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();
		
		//Set var
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransfer= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if (!$canTransfer) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}
		
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$transferred= JRequest::getVar( 'transfer_id', 0, 'post', 'int' );
		
		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVAL' ) );
		}

		$model = $this->getModel('Transactions');
		
		if(!$model->updateTransferring($cid, $transferred)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_APPROVAL_TRANSFERRED' );			
		}
		
		$mainframe->enqueueMessage($msg);

		return $this->execute('requestapproval');	
	}

	/**
	 * Logic to sumbit transfer success
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/
	function success() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;
		
		// Initialise variables
		$db			= & JFactory::getDBO();
		$app		= & JFactory::getApplication();
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransferred	= Ownservice::checkAccess('transaction', 'transferred', 'transaction', 'all');
			if ( !$canTransferred ){
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//set vars
		$cid		= JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$comment	= JRequest::getVar( 'comment', array(0), 'post', 'array');
		
		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_ITEM_TRANSFER_SUCCESS' ) );
		}

		$model = $this->getModel('Transactions');
		
		if(!$model->updateSuccess($cid, $comment)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' . JText::_( 'OWNSERVICE_TRANSFER_SUCCESSFUL' );
		}

		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect($link, $msg);
	}

	/**
	 * Logic to sumbit transfer fail
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/
	function fail() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;

		// Initialise variables
		$db			= & JFactory::getDBO();
		$app		= & JFactory::getApplication();
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransferred	= Ownservice::checkAccess('transaction', 'transferred', 'transaction', 'all');
			if ( !$canTransferred ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		$cid		= JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$comment	= JRequest::getVar( 'comment', array(0), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_ITEM_TRANSFER_FAIL' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateFail($cid, $comment)){
			$msg =  $model->getError();	
		} else {
			$msg = count($cid) . ' ' . JText::_( 'OWNSERVICE_TRANSFER_FAILED' );
		}
		
		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect($link, $msg);
	}

	/**
	 * Download logic transfer
	 *
	 * @access public
	 * @since 1.0
	 */
	function download() {

		global $mainframe;

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransferred	= Ownservice::checkAccess('transaction', 'transferred', 'transaction', 'all');
			if ( !$canTransferred ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//Get data form the model
		$model	= $this->getModel('Transactions');
		$rows	= $model->getTransferring();
		
		require_once(JPATH_COMPONENT_SITE.DS.'classes'.DS.'PHPExcel.php');

		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
		
		// Set properties
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
							 ->setLastModifiedBy("Maarten Balliauw")
							 ->setTitle("Office 2007 XLSX Test Document")
							 ->setSubject("Office 2007 XLSX Test Document")
							 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
							 ->setKeywords("office 2007 openxml php")
							 ->setCategory("Test result file");

		//Set default font
		$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('Arial');
		$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(8);

		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);

		// Set row height
		$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(30);

		//Add Some data
		$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Receipt No.')
			->setCellValue('B1', 'Account No.')
			->setCellValue('C1', 'Account Name')
			->setCellValue('D1', 'Account Type')
			->setCellValue('E1', 'Bank Name')
			->setCellValue('F1', 'Branch City')
			->setCellValue('G1', 'Sender')
			->setCellValue('H1', 'Transfer Amount (AUS)')
			->setCellValue('I1', 'Rate')
			->setCellValue('J1', 'Total Receivable')
			->setCellValue('K1', 'Distributed Date');


		if( count($rows) >= 1 ) {
			$i = 2;
			foreach($rows as $row) {
				$total = 0;
				if($row->extratotal > 0.00 ) {
					$total = $row->extratotal;
				} else {
					$total = $row->amount * ($row->rate+$row->extrarate);
				}
				
				$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A'.$i, $row->invoice)
					->setCellValue('B'.$i, OwnserviceHelper::accountFormat($row->account))
					->setCellValue('C'.$i, $row->account_name)
					->setCellValue('D'.$i, ucfirst($row->account_type))
					->setCellValue('E'.$i, $row->bank_name)
					->setCellValue('F'.$i, $row->branch_city)
					->setCellValue('G'.$i,  $row->username)
					->setCellValue('H'.$i, $row->amount)
					->setCellValue('I'.$i, ($row->rate+$row->extrarate).' '.$row->rate_code)
					->setCellValue('J'.$i, $total.' '.$row->rate_code)
					->setCellValue('K'.$i, date('d/m/Y', strtotime($row->requested_date)));
					
				$i++;
			}
		}

		// Freeze panes
		$objPHPExcel->getActiveSheet()->freezePane('A2');

		// Set style on cell
		$objPHPExcel->getActiveSheet()->getStyle('A1:K1')->applyFromArray(
			array(
				'alignment' => array(
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				'wrap'=>true,
				)
			)
		);

		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);

		// Redirect output to a client’s web browser (Excel2007)
		//header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		//header('Content-Disposition: attachment;filename="'.date('d-m-Y').'TRANSFER.xlsx"');
		//header('Cache-Control: max-age=0');

		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		//$objWriter->save('php://output');
		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date('d-m-Y').'TRANSFER.xls"');
		header('Cache-Control: max-age=0');
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
	}

	/**
	 * Method to fetch the members form
	 * 
	 * @since 1.5
	 */
	function viewmembers()
	{
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		$user =&JFactory::getUser();

		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		//header("Content-type:text/json");

		$model 			=  $this->getModel('Transaction');
		$memberobjs 	=  $model->getmembers(JRequest::getVar('q'));
		$array = array();
		echo "[";
		foreach($memberobjs as $member) {
			$array[] = "{\"id\":\"".$member->id."\",\"name\":\"".$member->username.' '.$member->name."\"}";
		}
		echo implode(",", $array);
		echo "]";
		exit;
	}

	/**
	 * Method to get Image of Member
	 * 
	 * @access public
	 * @return string
	 * @since 1.5
	 */
	 function getImage()
	 {
	 	// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		$id  = JRequest::getVar('id', 0 , 'post', 'int');

		$model 			=  $this->getModel('Transaction');
		
		$image 			=  $model->getImage($id);
		
		//resize image
		$path	= OwnserviceHelper::getParams('path', 'images/stories/ownservices');
		$info 	= @getimagesize(JPATH_SITE.DS.$path.DS.$image->userid.DS.$image->filename);
		if (($info[0] > 200) || ($info[1] > 200)) {
			$dimensions		= OwnserviceHelper::imageResize($info[0], $info[1], 200);
			$image->width	= $dimensions[0];
			$image->height	= $dimensions[1];
		} else {
			$image->width	= $info[0];
			$image->width	= $info[1];
		}
		if($image->filename){
			echo '<a class="img-preview" href="'.JURI::root(true).'/'.OwnserviceHelper::getParams('path', 'images/stories/ownservices').'/'.$id.'/'.$image->filename.'">';
				echo '<img src="'.JURI::root(true).'/'.OwnserviceHelper::getParams('path', 'images/stories/ownservices').'/'.$id.'/'.$image->filename.'" style="border: 0; width:'.$image->width.'px; height:'.$image->height.'px;" />';
			echo '</a>';
		}
		exit;
	 }

	/**
	 * Method to check expire of user
	 * 
	 * @access public
	 * @return json string
	 * @since 1.5
	 */
	 function checkexpire()
	 {
	 	// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		$id  	= JRequest::getVar('id', 0 , 'post', 'int');
		
		$model 	=  $this->getModel('Transaction');
		
		$user	= $model->getUser($id);
		
		$curentdate	= mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		list($edy, $edm, $edd)	= explode('-', $user->expire_date);
		$expiredate = mktime(0, 0, 0, $edm, $edd, $edy);
		
		$days = ($expiredate - $curentdate) / 86400;		
		
		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		//header("Content-type:text/json");
		
		echo "{\"days\":\"".$days."\", \"expiredate\":\"".$user->expire_date."\",\"id\":\"".$user->id."\"}";
		exit();
	 }
	 
	 /**
	  * Method to get transaction cancelled detail
	  * 
	  * @return void
	  * @since 1.0
	  */
	  function detailcancelled()
	  {
	  	global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		$id 		= JRequest::getVar('id');
		
		if($user->gid < 25) {
			$canView	= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');
		
		//update read cancelled
		$model->readCancelled($id);
		
		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('detailcancelled');

		// Display the view
		$view->display();
	  }
	  
	 /**
	 * Logic to set transfer cancelled
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/
	function cancelled() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;
		
		// Initialise variables
		$db			= & JFactory::getDBO();
		$app		= & JFactory::getApplication();
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) {
			$manage = Ownservice::checkAccess( 'transaction', 'manage' );
			if ( !$manage ){
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//set vars
		$id		= JRequest::getVar( 'id', 0, 'post', 'int' );
	
		$model = $this->getModel('Transactions');
		
		if(!$model->updateCancelled($id)){
			$msg = $model->getError();
		} else {
			$msg = JText::_( 'OWNSERVICE_TRANSACTION_CANCELLED' );
		}

		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect($link, $msg);
	}
}